<script lang="ts" setup>
import { onMounted, ref, toRefs, watch } from 'vue'
import { randomString } from '@/utils/string'

const props = defineProps({
  list: {
    type: Array,
    default: () => {
      return []
    },
  },
  isFooter: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['change'])

const { list } = toRefs(props)
const tableData: any = ref([])

onMounted(() => {
  tableData.value = readTree(JSON.parse(JSON.stringify(list.value)))
})

watch(list, (newValue) => {
  tableData.value = readTree(JSON.parse(JSON.stringify(newValue)))
})

function handleAdd() {
  const item = getItem()
  tableData.value.push(item)
  handleChange()
}

// function handleAddItem(row: any) {
//   const item = getItem()
//   if (!row.children) {
//     row.children = []
//   }
//   row.children.push(item)
//   handleChange()
// }

function getItem() {
  return {
    id: randomString(16),
    key: '',
    value: '',
    description: '',

  }
}

function handleDelete(row: any) {
  tableData.value = remoteChild(tableData.value, row.id)
  handleChange()
}

function remoteChild(data: any, id: string) {
  return data
    .filter((item: any) => item.id !== id)
    .map((item: any) => {
      if (item.children && item.children.length > 0) {
        item.children = remoteChild(item.children, id)
      }
      return item
    })
}

function handleDeleteAll(_index: any) {
  tableData.value = []
  handleChange()
}

function handleChange() {
  emit('change', tableData.value)
}

// id为null时设置默认id
function readTree(treeNodes: any, index: number | string = -1) {
  if (!treeNodes || !treeNodes.length)
    return []

  for (let idx = 0, len = treeNodes.length; idx < len; idx++) {
    const childs = treeNodes[idx].children
    const autoIdx = idx + 1
    // 为null时设置id
    if (treeNodes[idx].id === null) {
      if (index === -1) {
        treeNodes[idx].id = `${autoIdx}`
      }
      else {
        treeNodes[idx].id = `${index}_${autoIdx}`
      }
    }
    // 子项遍历
    if (childs && childs.length > 0) {
      if (index === -1) {
        readTree(childs, `${autoIdx}`)
      }
      else {
        readTree(childs, `${index}_${autoIdx}`)
      }
    }
  }
  return treeNodes
}

defineExpose({
  handleAdd,
})
</script>

<template>
  <section class="table-section">
    <el-table
      :data="tableData"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children' }"
      :border="true"
      header-cell-class-name="custom-table-header"
      :style="{ 'height': isFooter ? 'calc(100% - 40px)' : '100%', 'overflow-y': 'auto' }"
    >
      <el-table-column prop="key" label="键" class-name="mix-cell-class">
        <template #default="scope">
          <el-input v-model="scope.row.key" placeholder="请输入键" @change="handleChange" />
        </template>
      </el-table-column>
      <el-table-column prop="value" label="值">
        <template #default="scope">
          <el-input v-model="scope.row.value" placeholder="请输入值" @change="handleChange" />
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述">
        <template #default="scope">
          <el-input v-model="scope.row.description" placeholder="请输入描述" @change="handleChange" />
        </template>
      </el-table-column>
      <el-table-column prop="operate" label="操作" width="160" align="center">
        <template #default="scope">
          <!--
          <el-button type="primary" link @click="handleAddItem(scope.row)">
            添加
          </el-button>
          -->
          <el-button type="primary" link @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <footer v-if="isFooter" class="flex justify-center" style="margin-top: 8px">
      <el-button type="primary" plain @click="handleAdd">
        添加
      </el-button>
      <el-button type="danger" plain @click="handleDeleteAll">
        全部删除
      </el-button>
    </footer>
  </section>
</template>

<style lang="scss" scoped>
.table-section {
  height: 100%;
}

.table-section :deep() .mix-cell-class {
  div {
    display: flex !important;
    align-items: center !important;
  }
}
</style>
